<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Ability\ApiResponse;
use Hyperf\Context\Context;
use HyperfExt\Jwt\JwtFactory;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class JwtAuthMiddleware implements MiddlewareInterface
{
    use ApiResponse;
    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        try{

            $jwt = $this->container->get(JwtFactory::class)->make();

            $payload = $jwt->checkOrFail();

            Context::set("user_id",$payload->get("user_id"));

        }catch (\Exception $exception){

            if($exception instanceof \HyperfExt\Jwt\Exceptions\TokenExpiredException){//token过期
                $error = $this->error(111,"TokenExpiredException");
            }elseif($exception instanceof \HyperfExt\Jwt\Exceptions\InvalidClaimException){//token解析错误
                $error = $this->error(222,"InvalidClaimException");
            }elseif($exception instanceof \HyperfExt\Jwt\Exceptions\TokenInvalidException){
                $error = $this->error(333,"TokenInvalidException");
            }else{
                $error = $this->error(444,"Invalid JWT check");
            }
            return make(\Hyperf\HttpServer\Contract\ResponseInterface::class)->json($error);
        }

        return $handler->handle($request);
    }
}